package com.yh.threadTest.task;

import java.io.File;

/**
 * @ClassName Test3
 * @Description 管程法：生产者与消费者
 * @Author 0715-YuHao
 * @Date 2020/11/14 15:13
 */
public class Test3 {

    public static void main(String[] args) {
        FoodBuffer foodBuffer = new FoodBuffer();
        new Thread(new Chef(foodBuffer)).start();
        new Thread(new Waiter(foodBuffer)).start();
    }
}

//厨师
class Chef implements Runnable {

    FoodBuffer foodBuffer;

    public Chef(FoodBuffer foodBuffer) {
        this.foodBuffer = foodBuffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                foodBuffer.push(new Chicken(i));
                System.out.println("厨师生产了第" + i + "只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//服务员
class Waiter implements Runnable {

    FoodBuffer foodBuffer;

    public Waiter(FoodBuffer foodBuffer) {
        this.foodBuffer = foodBuffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                System.out.println("服务员拿走了第" + foodBuffer.pop().getId() + "鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//食物:烤鸡
class Chicken {
    private int id;

    public Chicken(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
//容器
class FoodBuffer {
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    public synchronized void push(Chicken chicken) throws InterruptedException {
        if (count == chickens.length) {
            this.wait();
        }
        chickens[count] = chicken;
        count++;
        this.notifyAll();
    }

    public synchronized Chicken pop() throws InterruptedException {
        if (count == 0) {
            this.wait();
        }
        count--;
        Chicken chicken = chickens[count];
        this.notifyAll();
        return chicken;
    }

}



